const { Router } = require('express')
const axios = require('axios')
const regisrty = require('./registry.json')
const fs = require('fs')

const router = Router()

router.all('/:apiName/:path', async (req, res) => {
  if (regisrty.services[req.params.apiName]) {
    const response = await axios({
      method: req.method,
      url: regisrty.services[req.params.apiName].url + req.params.path,
      headers: req.headers,
      data: req.body
    })

    res.send(response)
  }
})

router.post('/register', (req, res) => {
  const registrationInfo = req.body

  registrationInfo.url = `${registrationInfo.protocol}://${registrationInfo.host}:${registrationInfo.port}/`

  regisrty.services[registrationInfo.apiName] = { ...registrationInfo }

  fs.writeFile('./routes/registry.json', JSON.stringify(regisrty), (error) => {
    if (error) {
      return res.status(500).json({ message: `Could not register ${registrationInfo.apiName} \n ${error}` })
    } else {
      return res.status(200).json({ message: `Successfuly reistered ${registrationInfo.apiName}` })
    }
  })
})

module.exports = router
